package org.thanos.demo.service;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.UUID;

@Service("fileService")
public class FileServiceImpl implements FileService {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("YYYY-MM-dd");
    private static final String IMAGE_CONTENT_TYPE = "image/png;charset=utf-8";

    @Value("${base-dir}")
    private String baseDir;

    /**
     * 上传文件，对文件名加密
     *
     * @param file
     * @throws IOException
     */
    @Override
    public void uploadFile(MultipartFile file) throws IOException {
        String nowDir = LocalDateTime.now().format(FORMATTER);
        String originalFilename = file.getOriginalFilename();
        File desc = new File(baseDir + nowDir);
        if (!desc.exists()) {
            Files.createDirectory(Paths.get(baseDir + nowDir));
        }
        String prefixName = UUID.randomUUID().toString().replace("-", "");
        String suffixName = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf('.'));
        String fileName = prefixName + suffixName;
        Path path = Paths.get(baseDir + nowDir, fileName);
        Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
    }

    /**
     * 下载文件
     *
     * @param fileName
     * @param response
     */
    @Override
    public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        String nowDir = LocalDateTime.now().format(FORMATTER);
        fileName = baseDir + nowDir + '\\' + fileName;
        File file = new File(fileName);
        if (!(file.exists() && file.canRead())) {
            return;
        }
        byte[] buffer = new byte[1024];
        try (OutputStream outputStream = response.getOutputStream();
             FileInputStream inputStream = FileUtils.openInputStream(file);
             BufferedInputStream bis = IOUtils.buffer(inputStream))
        {
            response.setContentType(IMAGE_CONTENT_TYPE);
            int i = bis.read(buffer);
            while (i != -1) {
                outputStream.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            outputStream.flush();
        }
    }
}
